<?php
/**
 * 请求日志业务相关
 *
 * @author  
 * @time 2024-01-22 17:42:22
 */

namespace App\Repositories;

use App\Models\RequestLog;
use Illuminate\Support\Facades\Redis;

class RequestLogRepo
{
    const REQUEST_LOG_LIST = 'ai_law_request_log_list';

    private $redis;

    public function __construct()
    {
        $this->redis = Redis::connection('default');
    }

    public function getRequestLogListCacheKey()
    {
        return self::REQUEST_LOG_LIST;
    }

    /**
     * 定时批量入库
     *
     * @return void
     * @author  
     * @time 2024-01-22 19:57:05
     */
    public function cronStoreRequestLogCache()
    {
        $fetchLimit = 1000;
        $fetchLimitMin = 500;
        if (config('app.env') != 'production') {
            $fetchLimitMin = 1;
        }

        //存储标签搜索记录
        if ($length = $this->redis->llen(self::REQUEST_LOG_LIST)) {

            if ($length > 100000) {
                $length = 100000;
            }

            while ($length >= $fetchLimitMin) {
                $this->syncRequestLogCacheToDB($fetchLimit);
                $length -= $fetchLimit;
            }
        }
    }

    /**
     * 批量入库
     *
     * @param $fetchLimit
     * @return void
     * @author  
     * @time 2024-01-22 19:56:25
     */
    public function syncRequestLogCacheToDB($fetchLimit)
    {
        $requestLogs = $this->redis->lrange(self::REQUEST_LOG_LIST, 0, $fetchLimit);
        $this->redis->ltrim(self::REQUEST_LOG_LIST, $fetchLimit + 1, -1);
        $allInsert = [];
        foreach ($requestLogs as $log) {
            $allInsert[] = json_decode($log, true);
        }

        if ($allInsert) {
            (new RequestLog())->insertLog($allInsert);
        }
    }

}